﻿using AutoScaleHelper;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.ComponentModel;

namespace Tool
{
    public partial class Datax : Form
    {

        AutoScale autoScale = new AutoScale();
        public Datax()
        {
            InitializeComponent();
            autoScale.SetContainer(this);
        }

        private void Datax_Load(object sender, EventArgs e)
        {

        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            this.SuspendLayout();
            autoScale.UpdateControlsLayout();
            this.ResumeLayout();
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        private void DataLogText_TextChanged(object sender, EventArgs e)
        {

        }

        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            MessageBox.Show("同步脚本开始执行!");
            this.ConfirmButton.Enabled = false;
            this.Importbutton.Enabled = false;
            this.CancelButton.Enabled = false; 
            this.ImportHandlButton.Enabled = false;
            string dataHandlPathText = this.DataHandlPathText.Text;
            if (string.IsNullOrEmpty(dataHandlPathText))
            {
                MessageBox.Show("请选择导入文件!");
                this.ConfirmButton.Enabled = true;
                this.Importbutton.Enabled = true;
                this.CancelButton.Enabled = true;
                this.ImportHandlButton.Enabled = true;
                return;
            }
            string filePath = CreatJsonConfigFile();
            if (string.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("生成配置文件失败!");
                return;
            }
            else {
                //输出结果
                string strOuput = "";
                // 使用 BackgroundWorker 来执行耗时的后台操作
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (s, e1) =>
                {
                    // 在这里执行耗时的操作
                    // 注意：该代码不在 UI 线程上运行
                    string cmdCommand = "python " + dataHandlPathText + " " + filePath;
                    strOuput = ExecuteCmd(cmdCommand);
                };
                worker.RunWorkerCompleted += (s, e2) =>
                {
                    // 此事件处理器在 UI 线程上执行
                    if (e2.Error != null)
                    {
                        // 处理在 DoWork 事件中发生的任何异常
                    }
                    else
                    {
                        // 安全地更新 UI 线程上的控件
                        MessageBox.Show("同步脚本执行完毕!");
                        this.ConfirmButton.Enabled = true;
                        this.Importbutton.Enabled = true;
                        this.CancelButton.Enabled = true;
                        this.ImportHandlButton.Enabled = true;
                        this.DataLogText.Text = strOuput;
                    }
                };
                // 开始异步操作
                worker.RunWorkerAsync();
            }
        }

        /*
         * 创建Datax json 脚本文件
         */
        private string CreatJsonConfigFile()
        {
            string dataShowText = this.DataShowText.Text;
            if (string.IsNullOrEmpty(dataShowText))
            {
                MessageBox.Show("属性预览不能为空!");
                this.ConfirmButton.Enabled = true;
                this.Importbutton.Enabled = true;
                this.CancelButton.Enabled = true;
                this.ImportHandlButton.Enabled = true;
                return string.Empty;
            }
            else
            {
                string filename = Guid.NewGuid().ToString();
                string filePath = Directory.GetCurrentDirectory() + "\\jsonConfig" + "\\" + filename + ".json";
                var directory = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                // 创建文件并写入内容
                File.WriteAllText(filePath, dataShowText);
                return filePath;
            }
        }




        /**
         * 执行CMD 命令函数 
         */
        private string ExecuteCmd(string command)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            p.Start();
            p.StandardInput.WriteLine(command + "&exit");
            p.StandardInput.AutoFlush = true;
            string strOuput = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
            return strOuput;
        }

        private void Importbutton_Click(object sender, EventArgs e)
        {
            FileStream fsRead = null;
            try {
                //定义一个文件打开控件
                OpenFileDialog ofd = new OpenFileDialog();
                //设置打开对话框的初始目录，默认目录为桌面
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                //设置打开对话框的标题
                ofd.Title = "选择配置文件";
                //设置打开对话框可以多选
                ofd.Multiselect = true;
                //设置对话框打开的文件类型
                ofd.Filter = "配置文件|*.json";
                //设置对话框是否记忆之前打开的目录
                ofd.RestoreDirectory = true;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    //获取用户选择的文件完整路径
                    string filePath = ofd.FileName;
                    //获取对话框中所选文件的文件名和扩展名，文件名不包括路径
                    string fileName = ofd.SafeFileName;
                    using (fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
                    {
                        //定义二进制数组
                        byte[] buffer = new byte[1024 * 1024 * 5];
                        //从流中读取字节
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        string str_fileText = Encoding.Default.GetString(buffer, 0, r);
                        JsonSerializer serializer = new JsonSerializer();
                        TextReader tr = new StringReader(str_fileText);
                        JsonTextReader jtr = new JsonTextReader(tr);
                        object obj = serializer.Deserialize(jtr);
                        if (obj != null)
                        {
                            StringWriter textWriter = new StringWriter();
                            JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                            {
                                Formatting = Formatting.Indented,
                                Indentation = 4,//缩进字符数
                                IndentChar = ' '//缩进字符
                            };
                            serializer.Serialize(jsonWriter, obj);
                            this.DataShowText.Text = textWriter.ToString();
                        }
                    }
                    fsRead.Close();
                }
            } catch(JsonReaderException ex)
            {
                Console.WriteLine(ex.Message);
                this.DataShowText.Text = "";
                MessageBox.Show("配置文件格式不正确,应为JSON 格式!");
                fsRead.Close();
            }
        }

        private void ImportHandlButton_Click(object sender, EventArgs e)
        {
            //定义一个文件打开控件
            OpenFileDialog ofd = new OpenFileDialog();
            //设置打开对话框的初始目录，默认目录为桌面
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //设置打开对话框的标题
            ofd.Title = "选择执行文件";
            //设置打开对话框可以多选
            ofd.Multiselect = true;
            //设置对话框打开的文件类型
            ofd.Filter = "执行文件|*.py";
            //设置对话框是否记忆之前打开的目录
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //获取用户选择的文件完整路径
                string filePath = ofd.FileName;
                this.DataHandlPathText.Text = filePath.ToString();
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.DataShowText.Text = "";
            this.Close();
        }
    }
}
